import logging
from fastapi import FastAPI, Request, HTTPException
from fastapi_offline import FastAPIOffline
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware

from app.router import api_router
from utils.redis import RedisUtil
from utils.database import init_create_table
from app.log import register_logger

logger = logging.getLogger(__name__)

def create_app():
    """
    生成FatAPI对象
    :return:
    """
    # app = FastAPI()
    app = FastAPIOffline()

    # 后台api允许跨域
    app.add_middleware(
        CORSMiddleware,
        allow_origins="*",
        allow_credentials=True,
        allow_methods=["GET", "POST"],
        allow_headers=["*"],
    )

    register_logger(app)
    
    #启动事件
    @app.on_event('startup')
    async def startup() -> None:
        #初始化数据库
        init_create_table()
        #初始化redis
        # app.state.redis = await RedisUtil.create_redis_pool()
        app.state.redis_pool = await RedisUtil.create_redis_pool()
        pass
    
    #退出事件
    @app.on_event('shutdown')
    async def shutdown():
        #关闭redis
        # await RedisUtil.close_redis_pool(app)
        pass
        
    
    #全局异常处理
    @app.exception_handler(HTTPException)
    async def http_error_handler(req: Request, exc: HTTPException):
        if exc.status_code == 201:
            return JSONResponse({"code":0, "msg": exc.detail}, status_code=200)
        return JSONResponse({
            "code":exc.status_code,
            "msg": exc.detail,
            "data": []
        }, status_code=exc.status_code, headers=exc.headers)
    
    @app.exception_handler(RequestValidationError)
    async def request_validation_error_handler(_: Request, exc:RequestValidationError):

        return JSONResponse({
            "code": 500,
            "msg": '数据数据格式不正确',
            "data": exc.__str__()
        }, status_code=500)

    # 注册路由
    app.include_router(api_router)
    
    return app